package hotciv.view.tools;

import hotciv.framework.*;
import hotciv.view.*;
import hotciv.view.figures.UnitFigure;

import java.awt.event.MouseEvent;

import minidraw.framework.*;
import minidraw.standard.*;

/** A MiniDraw tool that can move units on the game world.
<#if type == "code">

<#include "/data/author.txt">
</#if>
*/

public class UnitMoveTool extends AbstractTool {

  private Game game;
  private int fLastX, fLastY; // previous mouse position
  private int fStartX, fStartY; // original mouse position
  private UnitFigure draggedFigure = null;

  public UnitMoveTool(DrawingEditor editor, Game game) {
    super(editor);
    this.game = game;
    draggedFigure = null;
  }

  public void mouseDown(MouseEvent e, int x, int y) {
    fStartX = x;
    fStartY = y;
    // find the figure that was directly under the (x,y) clicked...
    Figure f = editor.drawing().findFigure(e.getX(), e.getY());
    if (f instanceof UnitFigure) {
      editor.drawing().lock();
      draggedFigure = (UnitFigure) f;
      fLastX = x;
      fLastY = y;
    } 
  } 
  
  public void mouseDrag(MouseEvent e, int x, int y) {
    if (draggedFigure != null) {
      draggedFigure.moveBy(x - fLastX, y - fLastY);
      fLastX = x;
      fLastY = y;
    }
  }

  public void mouseUp(MouseEvent e, int x, int y) {
    if (draggedFigure != null) {
      editor.drawing().unlock();
      Position from = GfxConstants.getPositionFromXY(fStartX, fStartY);
      Position to = GfxConstants.getPositionFromXY(x, y);
      // ensure that the to position is within range due to
      // the precondition on game's moveUnit method.
      boolean valid = false;
      if ( to.getRow() >= 0 && to.getRow() < Game.WORLDSIZE && 
          to.getColumn() >= 0 && to.getColumn() < Game.WORLDSIZE ) {
        // position is valid, test if move is valid in the game 
        valid = game.moveUnit( from, to ); 
      } 
      if ( ! valid ) {
        int dx = fStartX - x;
        int dy = fStartY - y;
        draggedFigure.moveBy(dx, dy);
      }
    }
    draggedFigure = null;
  }

}
